package tiepbm.app.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import tiepbm.app.store.Common;
import tiepbm.app.store.activity.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.SmsManager;
import android.util.DisplayMetrics;

public class Util {

	private static char[] sSPECIAL_CHARACTERS = { ' ', '!', '"', '#', '$', '%',
			'*', '+', ',', ':', '<', '=', '>', '?', '@', '[', '\\', ']', '^',
			'`', '|', '~', 'À', 'Á', 'Â', 'Ã', 'È', 'É', 'Ê', 'Ì', 'Í', 'Ò',
			'Ó', 'Ô', 'Õ', 'Ù', 'Ú', 'Ý', 'à', 'á', 'â', 'ã', 'è', 'é', 'ê',
			'ì', 'í', 'ò', 'ó', 'ô', 'õ', 'ù', 'ú', 'ý', 'Ă', 'ă', 'Đ', 'đ',
			'Ĩ', 'ĩ', 'Ũ', 'ũ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ạ', 'ạ', 'Ả', 'ả', 'Ấ',
			'ấ', 'Ầ', 'ầ', 'Ẩ', 'ẩ', 'Ẫ', 'ẫ', 'Ậ', 'ậ', 'Ắ', 'ắ', 'Ằ', 'ằ',
			'Ẳ', 'ẳ', 'Ẵ', 'ẵ', 'Ặ', 'ặ', 'Ẹ', 'ẹ', 'Ẻ', 'ẻ', 'Ẽ', 'ẽ', 'Ế',
			'ế', 'Ề', 'ề', 'Ể', 'ể', 'Ễ', 'ễ', 'Ệ', 'ệ', 'Ỉ', 'ỉ', 'Ị', 'ị',
			'Ọ', 'ọ', 'Ỏ', 'ỏ', 'Ố', 'ố', 'Ồ', 'ồ', 'Ổ', 'ổ', 'Ỗ', 'ỗ', 'Ộ',
			'ộ', 'Ớ', 'ớ', 'Ờ', 'ờ', 'Ở', 'ở', 'Ỡ', 'ỡ', 'Ợ', 'ợ', 'Ụ', 'ụ',
			'Ủ', 'ủ', 'Ứ', 'ứ', 'Ừ', 'ừ', 'Ử', 'ử', 'Ữ', 'ữ', 'Ự', 'ự', };

	private static char[] sSPECIAL_CHARACTERS1 = { ' ', '!', '"', '#', '$',
			'%', '*', '+', ',', ':', '<', '=', '>', '?', '@', '[', '\\', ']',
			'^', '`', '|', '~', };

	private static char[] sREPLACEMENTS = { ' ', '!', '"', '#', '$', '%', '*',
			'+', ',', ':', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '`',
			'|', '~', 'A', 'A', 'A', 'A', 'E', 'E', 'E', 'I', 'I', 'O', 'O',
			'O', 'O', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'e', 'e', 'e', 'i',
			'i', 'o', 'o', 'o', 'o', 'u', 'u', 'y', 'A', 'a', 'D', 'd', 'I',
			'i', 'U', 'u', 'O', 'o', 'U', 'u', 'A', 'a', 'A', 'a', 'A', 'a',
			'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A',
			'a', 'A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e',
			'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'O',
			'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o',
			'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'U', 'u', 'U',
			'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', };

	private static char[] sSPECIAL_CHARACTERS_UNICODE = { 'À', 'Á', 'Â', 'Ã',
			'È', 'É', 'Ê', 'Ì', 'Í', 'Ò', 'Ó', 'Ô', 'Õ', 'Ù', 'Ú', 'Ý', 'à',
			'á', 'â', 'ã', 'è', 'é', 'ê', 'ì', 'í', 'ò', 'ó', 'ô', 'õ', 'ù',
			'ú', 'ý', 'Ă', 'ă', 'Đ', 'đ', 'Ĩ', 'ĩ', 'Ũ', 'ũ', 'Ơ', 'ơ', 'Ư',
			'ư', 'Ạ', 'ạ', 'Ả', 'ả', 'Ấ', 'ấ', 'Ầ', 'ầ', 'Ẩ', 'ẩ', 'Ẫ', 'ẫ',
			'Ậ', 'ậ', 'Ắ', 'ắ', 'Ằ', 'ằ', 'Ẳ', 'ẳ', 'Ẵ', 'ẵ', 'Ặ', 'ặ', 'Ẹ',
			'ẹ', 'Ẻ', 'ẻ', 'Ẽ', 'ẽ', 'Ế', 'ế', 'Ề', 'ề', 'Ể', 'ể', 'Ễ', 'ễ',
			'Ệ', 'ệ', 'Ỉ', 'ỉ', 'Ị', 'ị', 'Ọ', 'ọ', 'Ỏ', 'ỏ', 'Ố', 'ố', 'Ồ',
			'ồ', 'Ổ', 'ổ', 'Ỗ', 'ỗ', 'Ộ', 'ộ', 'Ớ', 'ớ', 'Ờ', 'ờ', 'Ở', 'ở',
			'Ỡ', 'ỡ', 'Ợ', 'ợ', 'Ụ', 'ụ', 'Ủ', 'ủ', 'Ứ', 'ứ', 'Ừ', 'ừ', 'Ử',
			'ử', 'Ữ', 'ữ', 'Ự', 'ự', };

	private static char[] sREPLACEMENTS_UNICODE = { 'A', 'A', 'A', 'A', 'E',
			'E', 'E', 'I', 'I', 'O', 'O', 'O', 'O', 'U', 'U', 'Y', 'a', 'a',
			'a', 'a', 'e', 'e', 'e', 'i', 'i', 'o', 'o', 'o', 'o', 'u', 'u',
			'y', 'A', 'a', 'D', 'd', 'I', 'i', 'U', 'u', 'O', 'o', 'U', 'u',
			'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A',
			'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'E', 'e',
			'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E',
			'e', 'I', 'i', 'I', 'i', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o',
			'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O',
			'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u',
			'U', 'u', 'U', 'u', };

	public static String toUrlFriendly(String s) {
		int maxLength = Math.min(s.length(), 8 * 1024);
		char[] buffer = new char[maxLength];
		int n = 0;
		for (int i = 0; i < maxLength; i++) {
			char ch = s.charAt(i);
			int index = Arrays.binarySearch(sSPECIAL_CHARACTERS, ch);
			if (index >= 0) {
				buffer[n] = sREPLACEMENTS[index];
			} else {
				buffer[n] = ch;
			}
			if (buffer[n] > 31) {
				n++;
			}
		}
		while (n > 0 && buffer[n - 1] == '/') {
			n--;
		}
		return String.valueOf(buffer, 0, n);
	}

	public static boolean CheckSpecialCharacter(String s) {
		boolean check = false;
		int maxLength = Math.min(s.length(), 236);
		for (int i = 0; i < maxLength; i++) {
			char ch = s.charAt(i);
			int index = Arrays.binarySearch(sSPECIAL_CHARACTERS1, ch);
			if (index >= 0) {
				check = true;
			}
		}
		return check;
	}

	public static boolean CheckSpaceCharacter(String s) {
		boolean check = false;
		char[] space = { ' ' };
		int maxLength = Math.min(s.length(), 236);
		for (int i = 0; i < maxLength; i++) {
			char ch = s.charAt(i);
			int index = Arrays.binarySearch(space, ch);
			if (index >= 0) {
				check = true;
			}
		}
		return check;
	}

	public static boolean CheckFullName(String s) {

		boolean check = false;
		Pattern localPattern = Pattern.compile("^[A-Za-z0-9\\s]*$");
		if (!localPattern.matcher(s).matches())
			check = true;
		return check;
	}

	public static boolean CheckUniCode(String s) {
		// boolean check = false;
		// int maxLength = Math.min(s.length(), 236);
		// for (int i = 0; i < maxLength; i++) {
		// char ch = s.charAt(i);
		// int index = Arrays.binarySearch(SPECIAL_CHARACTERS, ch);
		// if (index >= 0) {
		// check = true;
		// }
		// }
		// return check;
		boolean check = false;
		Pattern localPattern = Pattern.compile("^[A-Za-z0-9]*$");
		if (!localPattern.matcher(s).matches())
			check = true;
		return check;
	}

	
	public static boolean isTimeout(long time, int SMS_Timeout) {
		return (time > SMS_Timeout);
	}

	/**
	 * This method convets dp unit to equivalent device specific value in
	 * pixels.
	 * 
	 * @param dp
	 *            A value in dp(Device independent pixels) unit. Which we need
	 *            to convert into pixels
	 * @param context
	 *            Context to get resources and device specific display metrics
	 * @return A float value to represent Pixels equivalent to dp according to
	 *         device
	 */
	public static float convertDpToPixel(float dp, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	/**
	 * This method converts device specific pixels to device independent pixels.
	 * 
	 * @param px
	 *            A value in px (pixels) unit. Which we need to convert into db
	 * @param context
	 *            Context to get resources and device specific display metrics
	 * @return A float value to represent db equivalent to px value
	 */
	public static float convertPixelsToDp(float px, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float dp = px / (metrics.densityDpi / 160f);
		return dp;

	}

	public static String byteArrayToString(byte[] ar) {
		StringBuffer s = new StringBuffer();

		int j = ar.length; // for speed
		for (int i = 0; i < j; i++) {
			String t = Integer.toHexString(ar[i] >= 0 ? ar[i] : ar[i] + 256);
			if (t.length() < 2) {
				t = "0" + t;
			}
			s.append(t);
		}
		return s.toString();
	}

	public static int[] decodeZoomLevels(String encodedZoomLevels) {
		int[] out = new int[encodedZoomLevels.length()];
		int index = 0;

		for (char c : encodedZoomLevels.toCharArray())
			out[index++] = c - '?';
		return out;

	}

	public static boolean isNullOrEmpty(String string) {
		if (string == null || string.length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	
	public static String postData(String URL) throws Exception {
		BufferedReader in = null;
		InputStreamReader is = null;
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 10000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		int timeoutSocket = 10000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		String dataout = "";
		try {
			HttpClient client = new DefaultHttpClient(httpParameters);
			HttpGet request = new HttpGet();
			request.setURI(new URI(URL));
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			dataout = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		return dataout;
	}

	
	public static boolean isOnline(Context c) {
		ConnectivityManager cm = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	/*
	 * public static void setTypeNetwork(Context context, Global global) {
	 * ConnectivityManager cm = (ConnectivityManager) context
	 * .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo =
	 * cm.getActiveNetworkInfo(); if (Util.isOnline(context)) {
	 * global.setTypeNetwork(netInfo.getType()); } }
	 * 
	 * public static boolean checkTypeNetword(Context context, Global global) {
	 * ConnectivityManager cm = (ConnectivityManager) context
	 * .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo =
	 * cm.getActiveNetworkInfo(); if (netInfo.getType() ==
	 * global.getTypeNetwork()) return true; else return false; }
	 */

	public static void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static boolean isNetworking(Context c) {
		ConnectivityManager cm = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	public static String[] split(String str, String c) {
		String r[] = null;
		if (str != null) {
			int lenght = str.length();
			int first = 0;
			Vector lista = new Vector();
			if (str.indexOf(c) != -1) {
				for (int i = 0; i < lenght; i++) {
					if (i + c.length() <= lenght) {
						if (str.substring(i, i + c.length()).equals(c)) {
							lista.addElement(str.substring(first, i));
							first = i + c.length();
						}
					}
				}
				if (!str.endsWith(c)) {
					lista.addElement(str.substring(first, lenght));
				}
			} else {
				lista.addElement(str);
			}
			r = new String[lista.size()];
			for (int i = 0; i < lista.size(); i++) {
				r[i] = lista.elementAt(i).toString();
			}
		}
		return r;
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	// 20:00:00 - > 20:00
	public static String convertTime(String time) {
		return time.split(":")[0] + ":" + time.split(":")[1];
	}

	

	/**
	 * return the dd/mm/yyyy of current month eg: 05/2002 --> 31/05/2002
	 * 
	 * @param strMonthYear
	 *            : input string mm/yyyy
	 * @return
	 */
	public static String getLastestDateOfMonth(String strMonthYear) {
		String strDate = strMonthYear;
		int i, nYear, nMonth, nDay;
		String strSub = null;

		i = strDate.indexOf("/");
		if (i < 0)
			return "";
		strSub = strDate.substring(0, i);
		nMonth = (new Integer(strSub)).intValue(); // Month begin from 0 value
		strDate = strDate.substring(i + 1);
		nYear = (new Integer(strDate)).intValue();

		boolean leapyear = false;
		if (nYear % 100 == 0) {
			if (nYear % 400 == 0)
				leapyear = true;
		} else if ((nYear % 4) == 0)
			leapyear = true;

		if (nMonth == 2) {
			if (leapyear) {
				return "29/02/" + nYear;
			} else
				return "28/02/" + nYear;
		} else {
			if ((nMonth == 1) || (nMonth == 3) || (nMonth == 5)
					|| (nMonth == 7) || (nMonth == 8) || (nMonth == 10)
					|| (nMonth == 12))
				if (nMonth >= 10)
					return "31/" + +nMonth + "/" + nYear;
				else
					return "31/" + "0" + nMonth + "/" + nYear;
			else if ((nMonth == 4) || (nMonth == 6) || (nMonth == 9)
					|| (nMonth == 11))
				if (nMonth >= 10)
					return "30/" + +nMonth + "/" + nYear;
				else
					return "30/" + "0" + nMonth + "/" + nYear;
		}
		return "";
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager conMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo i = conMgr.getActiveNetworkInfo();
		if (i == null) {
			return false;
		}
		if (!i.isConnected()) {
			return false;
		}
		if (!i.isAvailable()) {
			return false;
		}
		return true;
	}

	public static String get_TypeNetwork(Activity act) {
		String network_type = "UNKNOWN";// maybe usb reverse tethering
		NetworkInfo active_network = ((ConnectivityManager) act
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		if (active_network != null && active_network.isConnectedOrConnecting()) {
			if (active_network.getType() == ConnectivityManager.TYPE_WIFI) {
				network_type = "WIFI";
			} else if (active_network.getType() == ConnectivityManager.TYPE_MOBILE) {
				network_type = ((ConnectivityManager) act
						.getSystemService(Context.CONNECTIVITY_SERVICE))
						.getActiveNetworkInfo().getSubtypeName();
			}
		}
		return network_type;
	}

	public static boolean sendSMS(String phone, String sms) {
		try {
//			System.out.println("PHONE: " + phone);
//			System.out.println("SMS: " + sms);
			SmsManager smsManager = SmsManager.getDefault();
			smsManager.sendTextMessage(phone, null, sms, null, null);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void showDialog(int i, final Activity act) {
		String key = "";
		switch (i) {
		case Common.CODE_ERROR_DOWNLOAD:
			key = "Xảy ra lỗi trong quá trình download. Vui lòng thử lại";
			break;
		case Common.CODE_ERROR_CONNECT:
			key = "Lỗi kết nối. Vui lòng kiểm tra lại kết nối mạng";
			break;
		case Common.CODE_ERROR_DATA:
			key = "Nội dung bạn chọn chưa có dữ liệu";
			break;
		case 3:
			key = "Đăng nhập không thành công. Vui lòng thử lại";
			break;
		case Common.CODE_SIGNIN_FAIL:
			key = "Đăng ký không thành công. Vui lòng thử lại";
			break;
		case Common.CODE_LOGIN_SUCCESS:
			key = "Đăng ký thành công";
			break;
		case Common.CODE_ERROR_NO_LOGIN:
			key = "Bạn chưa đăng nhập. Vui lòng đăng nhập để sử dụng chức năng này.";
			break;
		default:
			break;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setMessage(key).setCancelable(true)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.setIcon(R.drawable.common_notification);
		alert.setTitle("Thông báo");
		alert.show();
	}

//	public static void showDialog(String msg, Activity act,boolean isRunning) {
//		AlertDialog alertDialog;
//		if (!isRunning) {
//			Log.e("activity isn't running");
//		} else {
//			if (alertDialog != null && alertDialog.isShowing()) {
//				alertDialog.dismiss();
//			}
//			AlertDialog.Builder builder = new AlertDialog.Builder(act);
//			builder.setTitle("Thông báo");
//			builder.setMessage(msg);
//			builder.setPositiveButton("Đóng",
//					new DialogInterface.OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.dismiss();
//						}
//					});
//			alertDialog = builder.create();
//			alertDialog.show();
//		}
////		Dialog dlog = new Dialog(act);
////		dlog.getWindow().setBackgroundDrawable(
////				new ColorDrawable(Color.argb(50, 255, 255, 255)));
////		AlertDialog.Builder builder = new AlertDialog.Builder(act);
////		builder.setMessage(msg);
////		builder.setPositiveButton("Đóng cửa sổ", new Dialog.OnClickListener() {
////			public void onClick(DialogInterface dialog, int which) {
////				dialog.dismiss();
////			}
////		});
////		// builder.show();
////		AlertDialog alert = builder.create();
////		alert.setIcon(R.drawable.common_notification);
////		alert.setTitle("Thông báo");
////		alert.show();
//	}

	public static boolean ketnoi(Context context) {
		// TODO Auto-generated method stub
		ConnectivityManager connec = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// ARE WE CONNECTED TO THE NET

		if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
				|| connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
				|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
				|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
			return true;

		} else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
				|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
			return false;

		}
		return false;
	}

	public static boolean checkJson(String json) {
		JSONObject jobject = null;
		try {
			jobject = new JSONObject(json);
		} catch (Exception e) {
		}
		if (jobject != null)
			return true;
		else
			return false;
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	public static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	public static boolean isSMSReceiveTimeout(long time) {
		return (time > 40000);
	}

	

	public static void writeFilePrivate(String name, String content, Activity ac) {
		Context ctx = ac.getApplicationContext();
		String str = content;
		if (readFilePrivate(name, ac) != null)
			str = "," + content;

		try {
			FileOutputStream fos = ctx
					.openFileOutput(name, Context.MODE_APPEND);
			fos.write(str.getBytes());
			// fos.write(content);
			fos.close();
		} catch (java.io.FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String readFilePrivate(String name, Activity ac) {
		Context ctx = ac.getApplicationContext();
		String key = null;
		try {
			StringBuilder inb = new StringBuilder();
			InputStreamReader inputReader = new InputStreamReader(
					ctx.openFileInput(name));
			int ch;
			while ((ch = inputReader.read()) != -1)
				inb.append((char) ch);
			key = inb.toString().trim();
			inputReader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return key;
	}

	public static Drawable getImage(String link) {
//		System.out.println(link);
		URLConnection url;
		Drawable drawAble = null;
		try {
			String srcName = link;
			url = new URL(link).openConnection();
			url.setConnectTimeout(5000);
			url.setReadTimeout(500);
			InputStream is = url.getInputStream();
			drawAble = Drawable.createFromStream(is, srcName);
			// return drawAble;
		} catch (Exception e) {
			e.printStackTrace();
			// return null;
		}
		return drawAble;
	}
//	public static Bitmap getBitmapFromURL(String link){
//		try {
//	        URL url = new URL(link);
//	        HttpGet httpRequest = null;
//
//	        httpRequest = new HttpGet(url.toURI());
//
//	        HttpClient httpclient = new DefaultHttpClient();
//	        HttpResponse response = (HttpResponse) httpclient
//	                .execute(httpRequest);
//
//	        HttpEntity entity = response.getEntity();
//	        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
//	        InputStream input = b_entity.getContent();
//
//	        Bitmap bitmap = BitmapFactory.decodeStream(input);
//	        return bitmap;
//	    } catch (Exception ex) {
//	    	ex.printStackTrace();
//	    	return null;
//	    }
//	}
//	 public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
//	        Bitmap bitmap = null;
//	        InputStream in = null;
//	        try {
//	            in = OpenHttpConnection(URL);
//	            bitmap = BitmapFactory.decodeStream(in, null, options);
//	            in.close();
//	        } catch (IOException e1) {
//	        }
//	        return bitmap;
//	    }
//
//	    private static InputStream OpenHttpConnection(String strURL)
//	            throws IOException {
//	        InputStream inputStream = null;
//	        URL url = new URL(strURL);
//	        URLConnection conn = url.openConnection();
//
//	        try {
//	            HttpURLConnection httpConn = (HttpURLConnection) conn;
//	            httpConn.setRequestMethod("GET");
//	            httpConn.connect();
//
//	            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//	                inputStream = httpConn.getInputStream();
//	            }
//	        } catch (Exception ex) {
//	        	ex.printStackTrace();
//	        }
//	        return inputStream;
//	    }
	public static boolean checkDateExp(String date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"dd/MM/yyyy HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		Date current = cal.getTime();
//		System.out.println("---> "+date);
		boolean isResult = false;
		try {
			Date d = dateFormat.parse(date);
			if (d.after(current))
				isResult = true;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println(isResult);
		return isResult;

	}

	public static boolean compareTime(String date, int time) {
		if (date.equals(""))
			return true;
		else {
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy/MM/dd HH:mm:ss");
			Calendar cal = Calendar.getInstance();
			Date current = cal.getTime();
			String date1[] = date.split(" ");
			int hh1 = Integer.parseInt((date1[1].split(":"))[0]);
			int mm1 = Integer.parseInt((date1[1].split(":"))[1]);
			int ss1 = Integer.parseInt((date1[1].split(":"))[2]);
			if ((ss1 + time) >= 60) {
				mm1++;
				ss1 = (ss1 + time) - 60;
			} else {
				ss1 = (ss1 + time);
			}
			String dd = date1[0] + " " + hh1 + ":" + mm1 + ":" + ss1;
			try {
				Date date_max = dateFormat.parse(dd);
				if (current.after(date_max))
					return true;
				else
					return false;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		}

	}
	public static void installApp(Context context,String url){
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(url)), "application/vnd.android.package-archive");
		context.startActivity(intent);
	}
	/* Checks if external storage is available for read and write */
	public static boolean isExternalStorageWritable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	        return true;
	    }
	    return false;
	}

	/* Checks if external storage is available to at least read */
	public static boolean isExternalStorageReadable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state) ||
	        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
	        return true;
	    }
	    return false;
	}
}
